package com.wy.mongo;

import com.wy.domain.User;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;


@Service
public class MongoUtil {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private GridFSBucket gridFSBucket;

    public void save(User user){
        mongoTemplate.save(user);
    }

    public User findByUserName(String name){
        return mongoTemplate.findOne(Query.query(Criteria.where("name").is(name)), User.class);
    }

    public void store(InputStream inputStream,String filename){
        gridFsTemplate.store(inputStream,filename);
    }


    public byte[] find(String filename){
        GridFSFile fsFile = gridFsTemplate.findOne(Query.query(Criteria.where("filename").is(filename)));
        GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fsFile.getObjectId());
        GridFsResource resource = new GridFsResource(fsFile,downloadStream);

        try {
            InputStream inputStream = resource.getInputStream();
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public  void delete(){
        mongoTemplate.dropCollection("fs.chunks");
        mongoTemplate.dropCollection("fs.files");
    }
}
